<template>
  <div>
    <el-card>
      <!-- 搜索区域 -->
      <div class="form_box">
        <el-form
          ref="searchForm"
          size="small"
          label-position="left"
          label-width="60px"
          :model="userSearch"
        >
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="部门">
                <el-select
                  @keyup.enter.native="handleSearch"
                  @clear="handleSearch"
                  clearable
                  v-model="userSearch.departmentId"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                    {{ item.name }}
                    <el-tag style="margin-left: 30px" size="mini"
                      >{{ item.total }}人</el-tag
                    >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="用户名">
                <el-input
                  clearable
                  @clear="handleSearch"
                  @keyup.enter.native="handleSearch"
                  v-model="userSearch.username"
                  placeholder="请输入用户名查询"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="用户名">
                <el-input
                  clearable
                  @clear="handleSearch"
                  @keyup.enter.native="handleSearch"
                  v-model="userSearch.email"
                  placeholder="请输入邮箱查询"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="性别">
                <el-radio-group v-model="userSearch.sex">
                  <el-radio label="1">男</el-radio>
                  <el-radio label="0">女</el-radio>
                  <el-radio label>全部</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="昵称">
                <el-input
                  clearable
                  @keyup.enter.native="handleSearch"
                  v-model="userSearch.nickname"
                  placeholder="请输入昵称查询"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-button size="small" @click="handleReset" icon="el-icon-search"
                >重置</el-button
              >
              <el-button
                size="small"
                type="primary"
                icon="el-icon-search"
                @click="handleSearch"
                >查询</el-button
              >
              <el-button
                @click="handleAdd"
                size="small"
                type="success"
                icon="el-icon-plus"
                v-permission="'user:add'"
                >添加</el-button
              >
              <el-button
                size="small"
                @click="handleExport"
                v-permission="'user:export'"
                icon="el-icon-download"
                >导出</el-button
              >
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- 表格区域 -->
      <div class="table_box">
        <el-table size="small" :data="userList" border stripe>
          <el-table-column align="center" prop="id" label="#">
          </el-table-column>
          <el-table-column align="center" prop="username" label="用户名">
          </el-table-column>
          <el-table-column align="center" prop="sex" label="性别">
            <template scope="scope">
              <el-tag type="success" v-if="scope.row.sex === 1">帅哥</el-tag>
              <el-tag type="danger" v-if="scope.row.sex === 0">美女</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="departmentName"
            label="所属部门"
          >
          </el-table-column>
          <el-table-column align="center" prop="birth" label="生日">
          </el-table-column>
          <el-table-column align="center" prop="email" label="邮箱">
          </el-table-column>
          <el-table-column align="center" prop="phoneNumber" label="电话">
          </el-table-column>
          <el-table-column
            v-permission="'user:status'"
            align="center"
            prop="status"
            label="是否禁用"
          >
            <template scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="changeUserStatus(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column align="center" width="200px" label="操作">
            <template scope="scope">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                v-permission="'user:edit'"
                @click="handleEdit(scope.row)"
              ></el-button>
              <el-button
                size="mini"
                type="danger"
                v-permission="'user:delete'"
                @click="handleDelete(scope.row.id)"
                icon="el-icon-delete"
              ></el-button>
              <el-tooltip
                class="item"
                effect="dark"
                content="分配权限"
                placement="top"
              >
                <el-button
                  size="mini"
                  type="warning"
                  @click="handleRoleShow(scope.row.id)"
                  v-permission="'user:assign'"
                  icon="el-icon-s-tools"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <pageTools
        :total="total"
        :paginationPage="userSearch.pageNum"
        :paginationPagesize="userSearch.pageSize"
        @pageChange="pageChange"
        @pageSizeChange="pageSizeChange"
      ></pageTools>
      <el-dialog
        :title="isEdit ? '编辑用户' : '新增用户'"
        :visible.sync="addFormShow"
        @close="handleClose"
      >
        <userAdd
          v-if="addFormShow"
          @close="handleClose"
          @getUserList="getUserList"
          :id="editId"
          :isEdit="isEdit"
        ></userAdd>
      </el-dialog>
      <el-dialog
        center
        :destroy-on-close="true"
        title="分配角色"
        :visible.sync="roleShow"
        @close="handleCloseRole"
      >
        <el-transfer
          :titles="['未拥有', '已拥有']"
          :button-texts="['到左边', '到右边']"
          v-model="defaultKeys"
          :data="Roledata"
          filterable
        ></el-transfer>
        <div slot="footer" style="display: flex; justify-content: center">
          <el-button @click="handleCloseRole">取 消</el-button>
          <el-button type="primary" @click="handleSumbitRole">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import userAdd from './userAdd.vue'
import { getDeptListApi } from '../../../api/department'
import {
  getUserListApi,
  exportUserListApi,
  deleteUserApi,
  updateStatusUserApi,
  getUserRolesApi,
  setUserRolesApi
} from '../../../api/user'
export default {
  components: {
    userAdd
  },
  name: 'User',
  data () {
    return {
      Roledata: [],
      defaultKeys: [],
      roleShow: false,
      roleId: null,
      addFormShow: false,
      userSearch: {
        sex: '',
        departmentId: null,
        pageNum: 1,
        pageSize: 5,
        username: '',
        nickname: '',
        email: '' // 部门id
      },
      total: 0,
      options: [],
      userList: [],
      isEdit: false,
      editId: null
    }
  },
  methods: {
    async changeUserStatus (row) {
      const res = await updateStatusUserApi(row.id, row.status)
      if (!res.success) return this.$notify.error(res.data.errorCode)
      this.$notify.success('更新成功')
      this.getUserList()
    },
    // 给用户分配角色
    async handleSumbitRole () {
      const res = await setUserRolesApi(this.roleId, this.defaultKeys)
      if (!res.success) return this.$notify.error('分配角色失败')
      this.$notify.success('分配角色成功')
      this.handleCloseRole()
    },
    // 获取用户的权限信息
    async handleRoleShow (id) {
      const res = await getUserRolesApi(id)
      if (!res.success) return this.$notify.error('获取失败')
      this.Roledata = res.data.roles
      this.defaultKeys = res.data.values
      this.roleId = id
      this.roleShow = true
    },
    // 删除
    handleDelete (id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.onDelete(id)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    async onDelete (id) {
      const res = await deleteUserApi(id)
      if (!res.success) return this.$notify.error(res.data.errorCode)
      this.getUserList()
      this.$notify.success('删除成功')
    },
    handleCloseRole () {
      this.roleShow = false
    },
    handleClose () {
      this.addFormShow = false
    },
    handleEdit (row) {
      this.isEdit = true
      this.addFormShow = true
      this.editId = row.id
    },
    handleAdd () {
      this.isEdit = false
      this.addFormShow = true
    },
    pageChange (val) {
      this.userSearch.pageNum = val
      this.getUserList()
    },
    pageSizeChange (val) {
      this.userSearch.pageSize = val
      this.getUserList()
    },
    // 获取部门信息
    async getDeps () {
      const res = await getDeptListApi()
      if (!res.success) return this.$message.error('获取失败')
      this.options = res.data
    },
    // 搜索
    handleSearch () {
      this.userSearch.pageNum = 1
      this.getUserList()
    },
    // 获取用户列表
    async getUserList () {
      const res = await getUserListApi(this.userSearch)
      if (!res.success) return this.$message.error('获取失败')
      this.userList = res.data.rows
      this.total = res.data.total
    },
    // 清空
    handleReset () {
      this.userSearch = {
        sex: '',
        departmentId: null,
        pageNum: 1,
        pageSize: 5,
        username: '',
        nickname: '',
        email: '' // 部门id
      }
      this.handleSearch()
    },
    // 导出
    async handleExport () {
      const res = await exportUserListApi()
      // 将二进制文件转化为可访问的url
      const url = window.URL.createObjectURL(res)
      // 创建一个a链接
      const a = document.createElement('a')
      // 将a标签插入到body
      document.body.appendChild(a)
      a.href = url
      a.download = '用户列表.xls'
      a.click()
      window.URL.revokeObjectURL(url)
    }
  },
  created () {
    this.getDeps()
    this.getUserList()
  }
}
</script>

<style lang='less' scoped>
.table_box {
  margin: 20px 0 0px 0;
}
</style>
